package com.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.module.commonui.R;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGAlertDialog;

public class MarqueeAlertView extends RelativeLayout {

    private TextView textView;

    private String label;

    private TGAlertDialog alertDialog;

    public MarqueeAlertView(@NonNull Context context) {
        this(context, null);
    }

    public MarqueeAlertView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MarqueeAlertView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void updateTopMargin(int value) {
        ViewGroup.LayoutParams marqueeAlertViewLP = getLayoutParams();
        if (marqueeAlertViewLP instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) marqueeAlertViewLP;
            lp.topMargin = value;
            setLayoutParams(lp);
        }
    }

    private void init() {
        inflate(getContext(), R.layout.widget_marquee_alert, this);
        setBackgroundColor(getContext().getResources().getColor(R.color.global_customize_fixed_color_error));
        textView = findViewById(R.id.error_alert_tv);

        setOnClickListener(v -> {

            dismissDialogIfNeeded();

            alertDialog = new TGAlertDialog(getContext())
                    .builder(R.layout.tange_dialog_custom_blue_btn)
                    .setCancelable(false)
                    .setTitle(ResourcesUtil.getString(R.string.server_alert_title))
                    .setMessage(label)
                    .setPositiveButton(ResourcesUtil.getString(R.string.sure), new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });

            alertDialog.show();
        });
    }

    public void dismissDialogIfNeeded() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }

    public void updateContent(String text) {
        label = text;
        textView.setText(text);
    }
}
